package cn.fintecher.pangolin.common.utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;

/**
 * 实体对象处理工具类
 */
public class ObjectFieldUtil {
   static Logger  logger= LoggerFactory.getLogger(ObjectFieldUtil.class);

    /**
     * 检测属性所有字段是否为空
     * @param o
     * @return
     */
    public static boolean allfieldIsNull(Object o){
        try{
            for(Field field:o.getClass().getDeclaredFields()){
                //把私有属性公有化
                field.setAccessible(true);
                Object object = field.get(o);
                if(object instanceof CharSequence){
                    if(StringUtils.isNotBlank((String) object)){
                        return false;
                    }
                }else{
                    if(Objects.nonNull(object)){
                        return false;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 将源对象不为空的值赋值给目标对象
     * @param sourceObj 源对象
     * @param targetObj 目标对象
     * @param exceptionMap 剔除校验字段
     */
    public static void setNotNullToObj(Object sourceObj, Object targetObj, Map<String,String> exceptionMap){
            for(Field field:sourceObj.getClass().getDeclaredFields()){
                try {
                    //把私有属性公有化
                    field.setAccessible(true);
                    Object object = field.get(sourceObj);
                    if(Objects.isNull(exceptionMap)){
                        setValue(targetObj, field, object);
                    }else {
                        if(!exceptionMap.containsKey(field.getName())){
                            setValue(targetObj, field, object);
                        }
                    }
                }catch (Exception e){
                 logger.error(e.getMessage(),e);
                }
            }
    }

    private static void setValue(Object targetObj, Field field, Object object) {
        try {
                if(Objects.nonNull(object) && StringUtils.isNotBlank(String.valueOf(object))){
                    Field targetField = targetObj.getClass().getDeclaredField(field.getName());
                    targetField.setAccessible(true);
                    targetField.set(targetObj, object);
                }
        }catch (Exception e){
            logger.info("匹配提示信息，可忽略"+e.getMessage());
        }

    }
}
